<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="写好 JS 条件语句的几条守则">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-01-07-several-rules-for-writing-js-conditional-statements/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="article:published_time" content="2019-01-07T09:57:25.000Z">
  <meta property="article:modified_time" content="2019-01-07T09:57:25.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="条件语句">
  <meta name="twitter:card" content="summary">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-01-07-several-rules-for-writing-js-conditional-statements/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>写好 JS 条件语句的几条守则 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A4%9A%E9%87%8D%E5%88%A4%E6%96%AD%E6%97%B6%E4%BD%BF%E7%94%A8-Array-includes"><span class="nav-number">1.</span> <span class="nav-text">多重判断时使用 Array.includes</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9B%B4%E5%B0%91%E7%9A%84%E5%B5%8C%E5%A5%97%EF%BC%8C%E5%B0%BD%E6%97%A9-Return"><span class="nav-number">2.</span> <span class="nav-text">更少的嵌套，尽早 Return</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B0%E5%92%8C%E8%A7%A3%E6%9E%84"><span class="nav-number">3.</span> <span class="nav-text">使用默认参数和解构</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93%E5%87%8F%E5%B0%91null%E7%9A%84%E6%A3%80%E6%9F%A5"><span class="nav-number">3.1.</span> <span class="nav-text">使用第三方库减少null的检查</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%80%BE%E5%90%91%E4%BA%8E%E5%AF%B9%E8%B1%A1%E9%81%8D%E5%8E%86%E8%80%8C%E4%B8%8D%E6%98%AFSwitch%E8%AF%AD%E5%8F%A5"><span class="nav-number">4.</span> <span class="nav-text">倾向于对象遍历而不是Switch语句</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8D%E6%9E%84%E8%AF%AD%E6%B3%95"><span class="nav-number">4.1.</span> <span class="nav-text">重构语法</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AF%B9-%E6%89%80%E6%9C%89-%E9%83%A8%E5%88%86-%E5%88%A4%E6%96%AD%E4%BD%BF%E7%94%A8Array-every-amp-Array-some"><span class="nav-number">5.</span> <span class="nav-text">对 所有&#x2F;部分 判断使用Array.every &amp; Array.some</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-01-07-several-rules-for-writing-js-conditional-statements/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              写好 JS 条件语句的几条守则
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-01-07 17:57:25" itemprop="dateCreated datePublished" datetime="2019-01-07T17:57:25+08:00">2019-01-07</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                  </span>
                </span>


                <span id="/blob/2019-01-07-several-rules-for-writing-js-conditional-statements/" class="post-meta-item leancloud_visitors" data-flag-title="写好 JS 条件语句的几条守则" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <blockquote>
              <p>英文：ecelyn Yeen 译文：眠云(杨涛)<br>github.com/dawn-plex/translate/blob/master/articles/5-Tips-to-Write-Better-Conditionals-in-JavaScript.md<br>在用 JavaScript 工作时，我们经常和条件语句打交道，这里有5条让你写出更好/干净的条件语句的建议。<br>转载地址：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/0Dsvp-n8lTco930tvW4-1w">https://mp.weixin.qq.com/s/0Dsvp-n8lTco930tvW4-1w</a></p>
            </blockquote>
            <h1 id="多重判断时使用-Array-includes"><a href="#多重判断时使用-Array-includes" class="headerlink" title="多重判断时使用 Array.includes"></a>多重判断时使用 Array.includes</h1>
            <p>让我们看一下下面这个例子:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// condition</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (fruit == <span class="string">&#x27;apple&#x27;</span> || fruit == <span class="string">&#x27;strawberry&#x27;</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>第一眼，上面这个例子看起来没问题。如果我们有更多名字叫 <code>cherry</code> 和 <code>cranberries</code> 的红色水果呢？我们准备用更多的 <code>||</code> 来拓展条件语句吗？</p>
            <p>我们可以用 <code>Array.includes (Array.includes)</code>重写条件语句。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> redFruits = [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>, <span class="string">&#x27;cherry&#x27;</span>, <span class="string">&#x27;cranberries&#x27;</span>];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (redFruits.includes(fruit)) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>我们把红色的水果(red fruits)这一判断条件提取到一个数组。这样一来，代码看起来更整洁。</p>
            <h1 id="更少的嵌套，尽早-Return"><a href="#更少的嵌套，尽早-Return" class="headerlink" title="更少的嵌套，尽早 Return"></a>更少的嵌套，尽早 Return</h1>
            <p>让我们拓展上一个例子让它包含两个条件。</p>
            <ul>
              <li>如果没有传入参数 <code>fruit</code>，抛出错误</li>
              <li>接受 <code>quantity</code> 参数，并且在 <code>quantity</code> 大于 10 时打印出来</li>
            </ul>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit, quantity</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> redFruits = [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>, <span class="string">&#x27;cherry&#x27;</span>, <span class="string">&#x27;cranberries&#x27;</span>];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件 1: fruit 必须有值</span></span><br><span class="line">  <span class="keyword">if</span> (fruit) &#123;</span><br><span class="line">    <span class="comment">// 条件 2: 必须是red的</span></span><br><span class="line">    <span class="keyword">if</span> (redFruits.includes(fruit)) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 条件 3: quantity大于10</span></span><br><span class="line">      <span class="keyword">if</span> (quantity &gt; <span class="number">10</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;big quantity&#x27;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;No fruit!&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试结果</span></span><br><span class="line">test(<span class="literal">null</span>); <span class="comment">// error: No fruits</span></span><br><span class="line">test(<span class="string">&#x27;apple&#x27;</span>); <span class="comment">// print: red</span></span><br><span class="line">test(<span class="string">&#x27;apple&#x27;</span>, <span class="number">20</span>); <span class="comment">// print: red, big quantity</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>在上面的代码, 我们有:</p>
            <ul>
              <li>1个 if/else 语句筛选出无效的语句</li>
              <li>3层if嵌套语句 (条件 1, 2 &amp; 3)</li>
            </ul>
            <p>我个人遵循的规则一般是在发现无效条件时，尽早<code>Return</code>。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">/_ 当发现无效语句时，尽早Return _/</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit, quantity</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> redFruits = [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>, <span class="string">&#x27;cherry&#x27;</span>, <span class="string">&#x27;cranberries&#x27;</span>];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件 1: 尽早抛出错误</span></span><br><span class="line">  <span class="keyword">if</span> (!fruit) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;No fruit!&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件 2: 必须是红色的</span></span><br><span class="line">  <span class="keyword">if</span> (redFruits.includes(fruit)) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 条件 3: 必须是大质量的</span></span><br><span class="line">    <span class="keyword">if</span> (quantity &gt; <span class="number">10</span>) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;big quantity&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这样一来，我们少了一层嵌套语句。这种编码风格非常好，尤其是当你有很长的<code>if</code>语句的时候(想象你需要滚动到最底层才知道还有<code>else</code>语句，这并不酷)</p>
            <p>我们可以通过 <code>倒置判断条件</code> &amp; <code>尽早return</code> 进一步减少if嵌套。看下面我们是怎么处理判断 条件2 的:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">/_ 当发现无效语句时，尽早Return _/</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit, quantity</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> redFruits = [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>, <span class="string">&#x27;cherry&#x27;</span>, <span class="string">&#x27;cranberries&#x27;</span>];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件 1: 尽早抛出错误</span></span><br><span class="line">  <span class="keyword">if</span> (!fruit) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;No fruit!&#x27;</span>);</span><br><span class="line">  <span class="comment">// 条件 2: 当水果不是红色时停止继续执行</span></span><br><span class="line">  <span class="keyword">if</span> (!redFruits.includes(fruit)) <span class="keyword">return</span>; </span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件 3: 必须是大质量的</span></span><br><span class="line">  <span class="keyword">if</span> (quantity &gt; <span class="number">10</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;big quantity&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>通过倒置判断条件2，我们的代码避免了嵌套语句。这个技巧在我们需要进行很长的逻辑判断时是非常有用的，特别是我们希望能够在条件不满足时能够停止下来进行处理。</p>
            <p>而且这么做并不困难。问问自己，这个版本(没有嵌套)是不是比之前的(两层条件嵌套)更好，可读性更高？</p>
            <p>但对于我，我会保留先前的版本(包含两层嵌套)。这是因为:</p>
            <ul>
              <li>代码比较短且直接，包含if嵌套的更清晰</li>
              <li>倒置判断条件可能加重思考的负担(增加认知载荷)</li>
            </ul>
            <p>因此，应当尽力减少嵌套和尽早return，但不要过度。如果你感兴趣的话，可以看一下关于这个话题的一篇文章和 StackOverflow 上的讨论。</p>
            <ul>
              <li>Avoid Else, Return Early by Tim Oxley</li>
              <li>StackOverflow discussion on if/else coding style</li>
            </ul>
            <h1 id="使用默认参数和解构"><a href="#使用默认参数和解构" class="headerlink" title="使用默认参数和解构"></a>使用默认参数和解构</h1>
            <p>我猜下面的代码你可能会熟悉，在JavaScript中我们总是需要检查 null / undefined的值和指定默认值:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit, quantity</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!fruit) <span class="keyword">return</span>;</span><br><span class="line">  <span class="comment">// 如果 quantity 参数没有传入，设置默认值为 1</span></span><br><span class="line">  <span class="keyword">const</span> q = quantity || <span class="number">1</span>; </span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`We have <span class="subst">$&#123;q&#125;</span> <span class="subst">$&#123;fruit&#125;</span>!`</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//test results</span></span><br><span class="line">test(<span class="string">&#x27;banana&#x27;</span>); <span class="comment">// We have 1 banana!</span></span><br><span class="line">test(<span class="string">&#x27;apple&#x27;</span>, <span class="number">2</span>); <span class="comment">// We have 2 apple!</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>实际上，我们可以通过声明 默认函数参数 来消除变量 q。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit, quantity = <span class="number">1</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 如果 quantity 参数没有传入，设置默认值为 1</span></span><br><span class="line">  <span class="keyword">if</span> (!fruit) <span class="keyword">return</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`We have <span class="subst">$&#123;quantity&#125;</span> <span class="subst">$&#123;fruit&#125;</span>!`</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//test results</span></span><br><span class="line">test(<span class="string">&#x27;banana&#x27;</span>); <span class="comment">// We have 1 banana!</span></span><br><span class="line">test(<span class="string">&#x27;apple&#x27;</span>, <span class="number">2</span>); <span class="comment">// We have 2 apple!</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这更加直观，不是吗？注意，每个声明都有自己的默认参数.</p>
            <p>例如，我们也能给<code>fruit</code>分配默认值:<code>function test(fruit = &#39;unknown&#39;, quantity = 1)</code>。</p>
            <p>如果<code>fruit</code>是一个<code>object</code>会怎么样？我们能分配一个默认参数吗？</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit</span>) </span>&#123; </span><br><span class="line">  <span class="comment">// 当值存在时打印 fruit 的值</span></span><br><span class="line">  <span class="keyword">if</span> (fruit &amp;&amp; fruit.name)  &#123;</span><br><span class="line">    <span class="built_in">console</span>.log (fruit.name);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;unknown&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//test results</span></span><br><span class="line">test(<span class="literal">undefined</span>); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; &#125;); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;); <span class="comment">// apple</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>看上面这个例子，我们想打印 <code>fruit</code> 对象中可能存在的 <code>name</code> 属性。否则我们将打印<code>unknown</code>。我们可以通过默认参数以及解构从而避免判断条件 <code>fruit &amp;&amp; fruit.name</code></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// 解构 - 仅仅获取 name 属性</span></span><br><span class="line"><span class="comment">// 为其赋默认值为空对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">&#123;name&#125; = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log (name || <span class="string">&#x27;unknown&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// test results</span></span><br><span class="line">test(<span class="literal">undefined</span>); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; &#125;); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;); <span class="comment">// apple</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>由于我们只需要 <code>name</code> 属性，我们可以用 <code>&#123;name&#125;</code> 解构出参数，然后我们就能使用变量 <code>name</code> 代替 <code>fruit.name</code>。</p>
            <p>我们也需要声明空对象 <code>&#123;&#125;</code> 作为默认值。如果我们不这么做，当执行 <code>test(undefined)</code> 时，你将得到一个无法对 <code>undefined</code> 或 <code>null</code> 解构的的错误。因为在 <code>undefined</code> 中没有 <code>name</code> 属性。</p>
            <h2 id="使用第三方库减少null的检查"><a href="#使用第三方库减少null的检查" class="headerlink" title="使用第三方库减少null的检查"></a>使用第三方库减少null的检查</h2>
            <p>如果你不介意使用第三方库，这有一些方式减少null的检查:</p>
            <ul>
              <li>使用 Lodash get函数</li>
              <li>使用Facebook开源的idx库(with Babeljs)</li>
            </ul>
            <p>这是一个使用<a target="_blank" rel="noopener" href="https://www.lodashjs.com/">Lodash</a>的例子:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">fruit</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 获取属性名，如果属性名不可用，赋默认值为 unknown</span></span><br><span class="line">  <span class="built_in">console</span>.log(__.get(fruit, <span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;unknown&#x27;</span>); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// test results</span></span><br><span class="line">test(<span class="literal">undefined</span>); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; &#125;); <span class="comment">// unknown</span></span><br><span class="line">test(&#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;); <span class="comment">// apple</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>你可以在jsbin运行demo代码。除此之外，如果你是函数式编程的粉丝，你可能选择使用 Lodash fp，Lodash的函数式版本(方法变更为get或者getOr)。</p>
            <h1 id="倾向于对象遍历而不是Switch语句"><a href="#倾向于对象遍历而不是Switch语句" class="headerlink" title="倾向于对象遍历而不是Switch语句"></a>倾向于对象遍历而不是Switch语句</h1>
            <p>让我们看下面这个例子，我们想根据 <code>color</code> 打印出水果:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">color</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 使用条件语句来寻找对应颜色的水果</span></span><br><span class="line">  <span class="keyword">switch</span> (color) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;red&#x27;</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>];</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;yellow&#x27;</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">&#x27;banana&#x27;</span>, <span class="string">&#x27;pineapple&#x27;</span>];</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;purple&#x27;</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">&#x27;grape&#x27;</span>, <span class="string">&#x27;plum&#x27;</span>];</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">      <span class="keyword">return</span> [];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// test results</span></span><br><span class="line">test(<span class="literal">null</span>); <span class="comment">// []</span></span><br><span class="line">test(<span class="string">&#x27;yellow&#x27;</span>); <span class="comment">// [&#x27;banana&#x27;, &#x27;pineapple&#x27;]</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>上面的代码看起来没有错误，但是我找到了一些累赘。用对象遍历实现相同的结果，语法看起来更简洁:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruitColor = &#123;</span><br><span class="line">  red: [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>],</span><br><span class="line">  yellow: [<span class="string">&#x27;banana&#x27;</span>, <span class="string">&#x27;pineapple&#x27;</span>],</span><br><span class="line">  purple: [<span class="string">&#x27;grape&#x27;</span>, <span class="string">&#x27;plum&#x27;</span>]</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">color</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> fruitColor[color] || [];</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>或者你也可以使用 Map实现相同的结果:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruitColor = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">  .set(<span class="string">&#x27;red&#x27;</span>, [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;strawberry&#x27;</span>])</span><br><span class="line">  .set(<span class="string">&#x27;yellow&#x27;</span>, [<span class="string">&#x27;banana&#x27;</span>, <span class="string">&#x27;pineapple&#x27;</span>])</span><br><span class="line">  .set(<span class="string">&#x27;purple&#x27;</span>, [<span class="string">&#x27;grape&#x27;</span>, <span class="string">&#x27;plum&#x27;</span>]);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">color</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> fruitColor.get(color) || [];</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>Map是一种在 ES2015 规范之后实现的对象类型，允许你存储 key 和 value 的值。</p>
            <p>但我们是否应当禁止switch语句的使用呢？答案是不要限制你自己。从个人来说，我会尽可能的使用对象遍历，但我并不严格遵守它，而是使用对当前的场景更有意义的方式。</p>
            <p>Todd Motto有一篇关于 switch 语句对比对象遍历的更深入的文章，你可以在这个地方阅读</p>
            <h2 id="重构语法"><a href="#重构语法" class="headerlink" title="重构语法"></a>重构语法</h2>
            <p>在上面的例子，我们能够用<code>Array.filter</code> 重构我们的代码，实现相同的效果。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;, </span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;strawberry&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;, </span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;banana&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;yellow&#x27;</span> &#125;, </span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;pineapple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;yellow&#x27;</span> &#125;, </span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;grape&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;purple&#x27;</span> &#125;, </span><br><span class="line">  &#123; <span class="attr">name</span>: <span class="string">&#x27;plum&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;purple&#x27;</span> &#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">color</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> fruits.filter(<span class="function"><span class="params">f</span> =&gt;</span> f.color == color);</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>有着不止一种方法能够实现相同的结果，我们以上展示了 4 种。</p>
            <h1 id="对-所有-部分-判断使用Array-every-amp-Array-some"><a href="#对-所有-部分-判断使用Array-every-amp-Array-some" class="headerlink" title="对 所有/部分 判断使用Array.every &amp; Array.some"></a>对 所有/部分 判断使用Array.every &amp; Array.some</h1>
            <p>这最后一个建议更多是关于利用 JavaScript Array 的内置方法来减少代码行数。看下面的代码，我们想要检查是否所有水果都是红色:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;banana&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;yellow&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;grape&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;purple&#x27;</span> &#125;</span><br><span class="line">  ];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> isAllRed = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 条件：所有水果都是红色</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> f <span class="keyword">of</span> fruits) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!isAllRed) <span class="keyword">break</span>;</span><br><span class="line">    isAllRed = (f.color == <span class="string">&#x27;red&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(isAllRed); <span class="comment">// false</span></span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>代码那么长！我们可以通过 <code>Array.every</code>减少代码行数:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;banana&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;yellow&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;grape&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;purple&#x27;</span> &#125;</span><br><span class="line">  ];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> isAllRed = fruits.every(<span class="function"><span class="params">f</span> =&gt;</span> f.color == <span class="string">&#x27;red&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(isAllRed); <span class="comment">// false</span></span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>现在更简洁了，不是吗？相同的方式，如果我们想测试是否存在红色的水果，我们可以使用 <code>Array.some</code> 一行代码实现。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;apple&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;banana&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;yellow&#x27;</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;grape&#x27;</span>, <span class="attr">color</span>: <span class="string">&#x27;purple&#x27;</span> &#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 条件：任何一个水果是红色</span></span><br><span class="line">  <span class="keyword">const</span> isAnyRed = fruits.some(<span class="function"><span class="params">f</span> =&gt;</span> f.color == <span class="string">&#x27;red&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(isAnyRed); <span class="comment">// true</span></span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>




          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5/" rel="tag"># 条件语句</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-01-04-clear-float/" rel="prev" title="清除浮动">
                  <i class="fa fa-chevron-left"></i> 清除浮动
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-01-08-hexo-article-catalog-style-adjustment/" rel="next" title="Hexo文章目录样式调整">
                  Hexo文章目录样式调整 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>